

package com.zy.service.Impl;

import com.zy.entity.Menu;
import com.zy.entity.RoleMenu;
import com.zy.entity.StaffBranchDp;
import com.zy.mapper.MenuMapper;
import com.zy.mapper.RoleMenuMapper;
import com.zy.mapper.StaffBranchDpMapper;
import com.zy.service.MenuService;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class MenuServiceImpl implements MenuService {
    @Resource
    MenuMapper menuMapper;

    @Resource
    RoleMenuMapper roleMenuMapper;

    public MenuServiceImpl() {
    }

    @Override
    public Menu getById(Integer id) {
        return (Menu)this.menuMapper.selectByPrimaryKey(id);
    }

    @Override
    public void save(Menu menu) {
        this.menuMapper.insert(menu);
    }

    @Override
    public void updateById(Menu menu) {
        this.menuMapper.updateByPrimaryKey(menu);
    }

    @Override
    public List<Menu> tree() {
        Menu menu = new Menu();
        menu.setMpid(0);
        List<Menu> oneMenu = this.menuMapper.select(menu);
        for (Menu oneMenu1 : oneMenu) {
            this.searchChild(oneMenu1, this.menuMapper.selectAll());
        }
        return oneMenu;
    }

    @Override
    public void delete(Integer id) {
        this.menuMapper.deleteByPrimaryKey(id);
    }

    @Override
    public List<String> getByAccountName(String accountName) {
        return this.menuMapper.getByAccountName(accountName);
    }

    @Override
    public List<Menu> getTreeByRoleId(Integer roleId) {
        List<Menu> oneMenu = this.menuMapper.getByRoleId(roleId);
        for (Menu oneMenu1 : oneMenu) {
            this.searchChild(oneMenu1, this.menuMapper.selectAll());
        }
        return oneMenu;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void setByRoleId(List<Integer> menuIds, Integer roleId) {
        RoleMenu roleMenu = new RoleMenu();
        roleMenu.setRid(roleId);
        roleMenuMapper.delete(roleMenu);
        for (Integer m : menuIds) {
            RoleMenu roleMenu1 = new RoleMenu();
            roleMenu1.setRid(roleId);
            roleMenu1.setMid(m);
            roleMenuMapper.insert(roleMenu1);
        }
    }


    private void searchChild(Menu menu1, List<Menu> allMenu) {
        ArrayList<Menu> child = new ArrayList();
        for (Menu menu : allMenu) {
            if (menu.getMpid().equals(menu1.getMid())) {
                this.searchChild(menu, allMenu);
                child.add(menu);
            }
        }
        menu1.setMenuList(child);
    }
}
